package main;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerFactoryConfigurationError;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import object.StudentList;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

import parsers.StudentListParser;

public class StudentListXMLGenerator {
	
	private String filepath;
	private StudentList students;
	
	public StudentListXMLGenerator(String filepath,StudentList students){
		this.filepath=filepath;
		this.students=students;
	}
	
	public void generate(){
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder=null;
		try {
			builder = factory.newDocumentBuilder();
		} catch (ParserConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        Document doc = builder.newDocument();
        StudentListParser sParser=new StudentListParser(students);
        Element studentListE=sParser.parse(doc);
        studentListE.setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
        studentListE.setAttribute("xsi:schemaLocation", "../xsd/StudentList.xsd");
        doc.appendChild(studentListE);
        
        Transformer t=null;
		try {
			t = TransformerFactory.newInstance().newTransformer();
		} catch (TransformerConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (TransformerFactoryConfigurationError e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        t.setOutputProperty(OutputKeys.INDENT,"yes");
        t.setOutputProperty(OutputKeys.METHOD, "xml");
        try {
			t.transform(new DOMSource(doc), new StreamResult(new FileOutputStream(new File(filepath))));
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (TransformerException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        
	}

}
